package com.java.pertar.verificationcode;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class Capator {

    @Autowired
    private CaptchaModle captchaModle;

    private static final Long DateTime_No = 30 * 60 * 1000L;

    @RequestMapping("/getcaptcha")
    public void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {

        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaModle.getWidth(), captchaModle.getLength());
        String s = lineCaptcha.getCode();
        session.setAttribute(captchaModle.getSession().getKey(), s);
        session.setAttribute(captchaModle.getSession().getDate(), new Date());
        lineCaptcha.write(response.getOutputStream());


    }


    @RequestMapping("/check")
    public boolean check(String s, HttpSession session) {
        if (!StringUtils.hasLength(s)) {
            return false;
        }
        String s1 = (String) session.getAttribute(captchaModle.getSession().getKey());
        Date d = (Date) session.getAttribute(captchaModle.getSession().getDate());
        if (s.equalsIgnoreCase(s1) && d != null && System.currentTimeMillis() - d.getTime() < DateTime_No) {
            return true;
        }

        return false;

    }
}
